<template>
  <el-dialog
      title="添加信息"
      v-model="dialogVisibleAdd"
      width="800px"
      @close="resetFormData"
  >
    <el-form ref="addDataForm" :model="addData" label-width="120px">
      <el-form-item
          v-for="(value, key) in add_courseadjustmentInfo"
          :key="key"
          :label="value.verbose_name"
          :prop="key"
          :rules="allrules[key]"
      >
        <component
            filterable
            allow-create
            :is="inputComponentForType(value, key)"
            v-model="addData[key]"
            v-bind="value.componentProps || {}"
        >
          <!-- 当组件为el-select时，渲染options -->
          <template v-if="inputComponentForType(value, key) === 'el-select'">
            <el-option
                v-for="option in value.choices"
                :key="option"
                :label="option"
                :value="option"
            ></el-option>
          </template>
        </component>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   :loading="SubmitAddLoading"
                   :disabled="SubmitAddLoading"
                   @click="handleSubmitAdd">{{ SubmitAddLoading ? '正在添加' : '确认' }}
        </el-button>
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

  <AddAuthor ref="addAuthorComponent" :Type="'add'"/>
</template>
<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from 'vue';
import setting from '@/setting.js';
import eventBus from "@/event-bus.js";
import {ElMessage} from "element-plus";
import AddAuthor from "@/components/Main/ReportManagement/AddAuthor.vue";
import global, {jsonApi} from "@/global.js";


const props = defineProps({
  isAdmin: {
    type: Boolean,
    required: true
  }
});
const allrules = {
  term: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  type: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
  ],
  change_type: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
  ],
  course_name: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  original_class: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  original_week: [
    {
      validator: (rule, value, callback) => {
        // 检查是否为单个数字或区间
        if (/^([1-9]|1[0-9])$/.test(value)) { // 单个数字，1到19
          return callback();
        } else if (/^(([1-9]|1[0-9])-([1-9]|1[0-9]))$/.test(value)) { // 数字区间，如1-2, 3-4等
          const [start, end] = value.split('-').map(num => parseInt(num, 10));
          // 确保起始数字小于结束数字且都在1-19范围内
          if (start < end && start >= 1 && end <= 19) {
            return callback();
          }
        }
        return callback(new Error('请输入1-19之间的数字或者类似1-2这样的区间（区间也必须在1-19内），如仅停课则不填写'));
      },
      trigger: 'blur'
    },
  ],
  original_class_time: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        // 正则表达式匹配星期几（一至日）和节次（1-13，可能是一个范围）
        const regex = /^(一|二|三|四|五|六|日)\/(\d{1,2}(-\d{1,2})?)$/;
        const match = value.match(regex);

        if (match) {
          // 提取节次部分
          const sessionPart = match[2];
          const sessions = sessionPart.split('-');

          // 检查单个节次是否在 1 到 13 的范围内
          if (sessions.length === 1) {
            const session = parseInt(sessions[0], 10);
            if (session >= 1 && session <= 13) {
              return callback();
            }
          } else if (sessions.length === 2) {
            // 检查节次范围是否在 1 到 13 的范围内，并且开始节次小于结束节次
            const startSession = parseInt(sessions[0], 10);
            const endSession = parseInt(sessions[1], 10);
            if (startSession >= 1 && endSession <= 13 && startSession < endSession) {
              return callback();
            }
          }
        }

        // 如果不匹配或节次不在范围内，则返回错误信息
        return callback(new Error('格式错误，请按照 星期/节次 格式，例： 二/1-3 '));
      },
      trigger: 'blur'
    }
    // 其他规则...
  ],
  original_room: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  new_room: [
    // 其他规则...

  ],
  new_week: [
    {
      validator: (rule, value, callback) => {
        // 检查是否为单个数字或区间
        if (/^([1-9]|1[0-9])$/.test(value)) { // 单个数字，1到19
          return callback();
        } else if (/^(([1-9]|1[0-9])-([1-9]|1[0-9]))$/.test(value)) { // 数字区间，如1-2, 3-4等
          const [start, end] = value.split('-').map(num => parseInt(num, 10));
          // 确保起始数字小于结束数字且都在1-19范围内
          if (start < end && start >= 1 && end <= 19) {
            return callback();
          }
        }
        return callback(new Error('请输入1-19之间的数字或者类似1-2这样的区间（区间也必须在1-19内），如仅停课则不填写'));
      },
      trigger: 'blur'
    },
  ],
  new_class_time: [
    {
      validator: (rule, value, callback) => {
        // 正则表达式匹配星期几（一至日）和节次（1-13，可能是一个范围）
        const regex = /^(一|二|三|四|五|六|日)\/(\d{1,2}(-\d{1,2})?)$/;
        const match = value.match(regex);

        if (match) {
          // 提取节次部分
          const sessionPart = match[2];
          const sessions = sessionPart.split('-');

          // 检查单个节次是否在 1 到 13 的范围内
          if (sessions.length === 1) {
            const session = parseInt(sessions[0], 10);
            if (session >= 1 && session <= 13) {
              return callback();
            }
          } else if (sessions.length === 2) {
            // 检查节次范围是否在 1 到 13 的范围内，并且开始节次小于结束节次
            const startSession = parseInt(sessions[0], 10);
            const endSession = parseInt(sessions[1], 10);
            if (startSession >= 1 && endSession <= 13 && startSession < endSession) {
              return callback();
            }
          }
        }

        // 如果不匹配或节次不在范围内，则返回错误信息
        return callback(new Error(',如仅停课则不填写，格式错误，请按照 星期/节次 格式，例： 二/1-3 '));
      },
      trigger: 'blur'
    }
    // 其他规则...
  ],
  reason_type: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
  ],
  reason: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  // 其他字段的规则...
  // 更多字段...
};

const courseadjustmentInfo = ref({});
const add_courseadjustmentInfo = ref({});
// 添加数据弹窗控制
let dialogVisibleAdd = ref(false);
let addData = reactive({});
const addDataForm = ref(null);
const SubmitAddLoading = ref(false);
const classroom = ref([]);
onMounted(() => {
  eventBus.on('course-adjustment-form-table-add', handleFormTableAdd);
});

onBeforeUnmount(() => {
  eventBus.off('course-adjustment-form-table-add', handleFormTableAdd);
});

//提交添加的数据
const handleSubmitAdd = async () => {
  SubmitAddLoading.value = true;
  // 在这里你可以处理表单提交逻辑
  //去除this.newData.author中元素为空的元素
  try {
    // 尝试使用当前的access_token获取数据
    let api_url = '';
    if (props.isAdmin) {
      api_url = '/courseadjustmentmanagement/addforadmin/';
    } else {
      api_url = '/courseadjustmentmanagement/add/';
    }
    const response = await jsonApi(api_url, JSON.stringify(addData));

    const data = await response.json();

    // 检查返回的数据是否包含错误信息，表明token可能无效或过期
    if (response.status === 201 || response.status === 200) {
      refresh();


      SubmitAddLoading.value = false;
      dialogVisibleAdd.value = false;

    } else {
      //执行父组件的方法
      // dialogVisibleAdd = false;
      ElMessage({
        type: 'error',
        message: data.error
      });
      SubmitAddLoading.value = false;

    }

    // 如果没有错误，则返回数据


  } catch (error) {
    // 网络错误或其他非token导致的错误
    SubmitAddLoading.value = false;
    throw error;
  }
}
// 使用defineEmits声明事件
const emit = defineEmits(['refresh-table']);

function refresh() {
  emit('refresh-table', {});
}

// 获取添加时的键信息
const getcourseadjustmentInfo = async () => {
  courseadjustmentInfo.value = JSON.parse(localStorage.getItem('CourseadJustmentInfo'))['TeacherChangeClassRecord'];
  console.log(courseadjustmentInfo.value);
  //获取增加时的字段
  add_courseadjustmentInfo.value = courseadjustmentInfo.value;
  let add_excludeFields = null;
  if (props.isAdmin) {
    add_excludeFields = ['id', 'model_name', 'revstatus', 'created_time', 'created_at', 'updated_at', 'attachment'];
  } else {
    add_excludeFields = ['id', 'teacher_id', 'teacher_name', 'model_name', 'revstatus', 'created_time', 'created_at', 'updated_at', 'attachment'];
  }
  add_excludeFields.forEach(field => {
    // 如果报告信息中存在要排除的字段，则删除它
    if (add_courseadjustmentInfo.value.hasOwnProperty(field)) {
      delete add_courseadjustmentInfo.value[field];
    }
  });
  for (let key in add_courseadjustmentInfo.value) {
    addData[key] = null;
  }
  //对部分键设置推荐信息
  addData['term'] = getSchoolTerm(new Date)


}


const handleFormTableAdd = () => {
  dialogVisibleAdd.value = true;
  getcourseadjustmentInfo()
};


const inputComponentForType = (value, key) => {
  const componentMap = {
    'CharField': 'el-input',
    'IntegerField': 'el-input',
    'DateTimeField': 'el-date-picker',
    'JSONField': 'el-textarea', // 使用文本域展示JSON字符串，并考虑设置为只读
    'BooleanField': 'el-switch',
    'TextField': 'el-input'
  };
  // 如果value.choices存在，则返回el-select组件并且附带options
  if (value.choices !== null) {
// 使用choice.label作为label，choice.value作为value
    return 'el-select'
  } else {
    // 直接返回组件类型，如果未找到则返回'未知类型'
    return componentMap[value.type] || 'el-input';
  }


};
// 重置表单数据
const resetFormData = () => {
  Object.keys(addData).forEach(key => {
    if (addData[key] instanceof File) {
      addData[key] = null;
    } else {
      addData[key] = '';
    }
  });
};

function showError(message, error, duration) {
  console.error(message, error);
  // 实现错误展示逻辑，例如使用通知组件
}

function getSchoolTerm(date) {
  const currentYear = date.getFullYear();
  const currentMonth = date.getMonth() + 1; // 月份是从0开始的

  // 确定学年
  let startYear, endYear;
  if (currentMonth >= 8 || currentMonth <= 1) { // 9月至次年2月属于秋季学期
    startYear = currentYear;
    endYear = currentYear + 1;
  } else { // 2月至7月属于春季学期
    startYear = currentYear - 1;
    endYear = currentYear;
  }

  // 确定学期
  let term;
  if (currentMonth >= 2 && currentMonth <= 7) {
    term = '春季学期';
  } else {
    term = '秋季学期';
  }

  return `${startYear}-${endYear}学年${term}`;
}

// 示例使用
const currentDate = new Date();
const schoolTerm = getSchoolTerm(currentDate);
console.log(schoolTerm); // 输出当前时间对应的学年学期描述

</script>
<style scoped>

</style>